<template>
    <Modal v-model="show" title="增加" @on-ok="ok" :loading="loading">
        <Form ref="userForm" :model="userForm" :rules="userFormRule">
            <Row>
                <Col span="24">
                    <FormItem label="所属组织" prop="orgName">
                        <Input type="text" :maxlength=50 v-model="userForm.orgName" disabled/>
                    </FormItem>
                </Col>
            </Row>
            <Row>
                <Col span="10">
                    <FormItem label="用户账号" prop="loginAccount">
                        <Input type="text" :maxlength=50 v-model="userForm.loginAccount" placeholder="请输入用户账号"/>
                    </FormItem>
                </Col>
                <Col span="4" style="text-align: center">&nbsp;&nbsp;</Col>
                <Col span="10">
                    <FormItem label="用户邮箱" prop="email">
                        <Input type="text" :maxlength=50 v-model="userForm.email" placeholder="请输入用户邮箱"/>
                    </FormItem>
                </Col>
            </Row>
            <Row>
                <Col span="10">
                    <FormItem label="用户名字" prop="userName">
                        <Input type="text" :maxlength=50 v-model="userForm.userName" placeholder="请输入用户名字"/>
                    </FormItem>
                </Col>
                <Col span="4" style="text-align: center">&nbsp;&nbsp;</Col>
                <Col span="10">
                    <FormItem label="用户性别" prop="sex">
                        <Row>
                            <Col span="24">
                                <RadioGroup v-model="userForm.sex">
                                    <Radio label="1">男</Radio>
                                    <Radio label="2">女</Radio>
                                </RadioGroup>
                            </Col>
                        </Row>
                    </FormItem>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <FormItem label="用户角色" prop="userRoles">
                        <Row>
                            <Col span="24">
                                <Select v-model="userForm.userRoles" multiple >
                                    <Option v-for="role in roleList" :value="role.roleId" :key="role.roleId">{{ role.roleName }}</Option>
                                </Select>
                            </Col>
                        </Row>
                    </FormItem>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <FormItem label="具体地址" prop="fullAddress">
                        <Row>
                            <Col span="24">
                                <Row>
                                    <Col span="10">
                                        <cascaderAddress @cascaderPick="cascaderAddressPick" :cascaderValue="cascaderValue" ></cascaderAddress>
                                    </Col>
                                    <Col span="14">
                                        <Input type="text" :maxlength=50 v-model="userForm.streetAddress" placeholder="请输入街道地址"/>
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                    </FormItem>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <FormItem label="头像地址" prop="avatorImgPath">
                        <Row>
                            <Col span="24">
                                <baseImgUpload ref="avatorImg" :maxLength="1" idImageType="user" :defaultList="defaultList" @getUploadList="getUserImgUploadList"></baseImgUpload>
                            </Col>
                        </Row>
                    </FormItem>
                </Col>
            </Row>
        </Form>
    </Modal>
</template>
<script>

    import {isExit,updateUser,getUser} from '../../../api/sys/user/user-api';
    import {getRoleList} from '../../../api/sys/role/role-api';
    import baseImgUpload from '../../../components/upload';
    import cascaderAddress from '../../../components/cascader-address';

    export default {
        name: 'addUser',
        components: {
            baseImgUpload,
            cascaderAddress
        },
        props: {
            value: {
                type: Boolean,
                default: false
            },
            userId: {
                type: String
            }
        },
        data() {
            return {
                loading:true,
                show:this.value,// vue2.0移除了props的双向绑定，因此我们需要在data中使用一个值来进行绑定
                roleList:[],
                userForm:{
                    userId:'',
                    orgName:'',
                    orgId:'',
                    avatorImgPath:'',
                    userName:'',
                    loginAccount:'',
                    sex:'1',
                    email:'',
                    provinceName:'',
                    provinceCode:'',
                    cityName:'',
                    cityCode:'',
                    areaName:'',
                    areaCode:'',
                    streetAddress:'',
                    fullAddress:'',
                    userRoles:[]
                },
                userFormRule:{
                    userName:[
                        {required: true, message: '请输入用户名字', trigger: 'blur'},
                        {type: 'string', max: 50, message: '用户名字允许输入最大长度为50个字符', trigger: 'blur'}
                    ],
                    loginAccount: [
                        {required: true, message: '请输入账号.', trigger: 'blur'},
                        {type: 'string', max: 10, message: '账号允许输入最大长度为10个字符', trigger: 'blur'},
                        {
                            validator: this.checkLoginAccount({
                                tip: '账号重复',
                                response: 'exist'
                            }), trigger: 'blur'
                        }
                    ],
                    avatorImgPath:[
                        {required: true, message: '请选择头像地址', trigger: 'blur'}
                    ],
                    email:[
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {type: 'string', max: 50, message: '邮箱允许输入最大长度为50个字符', trigger: 'blur'}
                    ],
                    fullAddress:[
                        {required: true, message: '请输入具体地址', trigger: 'blur'}
                    ]
                },
                defaultList:[],
                cascaderValue:[]
            };
        },
        methods:{
            checkLoginAccount(json){
                let _this = this;
                return function (rule, value, callback) {
                    let loginAccount = value;
                    let userId = _this.userForm.userId;
                    isExit({loginAccount,userId}).then(res => {
                        if (res.result) {
                            callback();
                        } else {
                            callback(new Error(json.tip ? json.tip : res.msg));
                        }
                    });
                };
            },
            cascaderAddressPick(val){
                if(val.length==0){
                    this.userForm.provinceName = '';
                    this.userForm.provinceCode = '';
                    this.userForm.cityName = '';
                    this.userForm.cityCode = '';
                    this.userForm.areaName = '';
                    this.userForm.areaCode = '';
                    return true;
                }
                // 判断当前从子组件传过来的数据是否是通过下拉获取的数据
                if(Object.prototype.toString.call(val[0]) === '[object Object]'){
                    this.userForm.provinceName = val[0].label;
                    this.userForm.provinceCode = val[0].value;
                    this.userForm.cityName = val[1].label;
                    this.userForm.cityCode = val[1].value;
                    if(val.length<=2){
                        this.userForm.areaName = val[1].label;
                        this.userForm.areaCode = val[1].value;
                    }else{
                        this.userForm.areaName = val[2].label;
                        this.userForm.areaCode = val[2].value;
                    }
                }
            },
            ok(){
                this.$refs['userForm'].validate((valid) => {
                    if (valid) {
                        updateUser(this.userForm).then(res => {
                            if(res.result){
                                this.$Message.success(res.msg);
                                // 提交表单数据成功则关闭当前的modal框
                                this.closeModal(false);
                                // 同时调用父页面的刷新页面的方法
                                this.$emit('handleSearch');
                            }else{
                                this.$Message.err(res.msg);
                            }
                        });
                    }else{
                        this.$Message.error('表单验证失败，请检查表单!');
                    }
                    setTimeout(() => {
                        this.loading = false;
                        this.$nextTick(() => {
                            this.loading = true;
                        });
                    },1000);
                });
            },
            getUserImgUploadList(val){
                if (val.length > 0) {
                    this.userForm.avatorImgPath = val[0].name;
                } else {
                    this.userForm.avatorImgPath = '';
                }
            },
            closeModal(val) {
                this.$emit('input', val);
            }
        },
        watch:{
            value(val){
                this.show = val;
            },
            show(val) {
                //当重新显示增加数据的时候重置整个form表单
                if(val){
                    this.$refs['userForm'].resetFields();
                    this.$refs['avatorImg'].cleanAll();
                    getUser({userId:this.userId}).then(res=>{
                        if(res.result){
                            this.userForm = res.entity;
                            this.defaultList = [
                                {
                                    name:this.userForm.avatorImgPath,
                                    url:this.$config.runConfig.imgUrl + '/' +this.userForm.avatorImgPath,
                                    status:'finished',
                                    percentage:100
                                }
                            ];
                            this.cascaderValue = [this.userForm.provinceCode,this.userForm.cityCode,this.userForm.areaCode];
                            getRoleList({'current':1,'pageSize':99999,'searchValue':''}).then(res => {
                                console.log(JSON.stringify(res))
                                if (res.result) {
                                    this.roleList = res.result;
                                }
                            });
                        }else{
                            this.$Message.success(res.msg);
                            this.closeModal(false);
                        }
                    });
                }else{// 反之则关闭页面
                    this.closeModal(val);
                }
            },
            'userForm.areaCode':function(val){// 监听地区编码值的变化，来写入具体的地址的数据
                if(val!=''&&this.userForm.streetAddress!=''){
                    this.userForm.fullAddress = this.userForm.provinceName + this.userForm.cityName + this.userForm.areaName + this.userForm.streetAddress;
                }else{
                    this.userForm.fullAddress = '';
                }
            },
            'userForm.streetAddress':function(val){// 监听街道地址数据的变化，来写入具体的地址的数据
                if(val!=''&&this.userForm.areaCode!=''){
                    this.userForm.fullAddress = this.userForm.provinceName + this.userForm.cityName + this.userForm.areaName + this.userForm.streetAddress;
                }else{
                    this.userForm.fullAddress = '';
                }
            }
        }
    };
</script>